<template>
	<view class="content">
		<view class="content_form">
			<uni-forms :modelValue="formData" ref="form" :rules="rules" :label-width="76">
				<LEditor v-model:value="formData.content" ref="lEditorRef" />
				<uni-forms-item label="收件人" prop="userRealName" required v-if="current == 0">
					<view style="width: 100%;margin-top: 10rpx;">
						<text style="color:#0960bd" @click="handleSelectUser(0)">选择</text>
						<text @click="handleCS" style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送'
						}}</text>
						<view class="cus_tag" style="margin-top: 10rpx;">
							<view class="cus_tag_view" v-for="(item, index) in formData['hadUsers']" :key="item.key">{{
								item.title }}
								<uni-icons type="closeempty" @click="handleCloseTag(index, 0)"
									color='#2979ff'></uni-icons>
							</view>
						</view>
					</view>
				</uni-forms-item>
				<template v-if="current == 1">
					<uni-forms-item label="部门" prop="userRealName" required>
						<view style="width: 100%;margin-top: 10rpx;">
							<text style="color:#0960bd" @click="handleTkiTreeDepart()">选择</text>
							<text @click="handleCS" style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送'
							}}</text>
							<view class="cus_tag" style="margin-top: 10rpx;">
								<view class="cus_tag_view" v-for="(item, index) in formData['hadDeptList']"
									:key="item.code">{{ item.name }}
									<uni-icons type="closeempty" @click="handleCloseTag(index, 3)"
										color='#2979ff'></uni-icons>
								</view>
							</view>
						</view>
					</uni-forms-item>
				</template>
				<uni-forms-item label="抄送" v-if="iscs">
					<view style="width: 100%;margin-top: 10rpx;">
						<text style="color:#0960bd" @click="handleSelectUser(1)">选择</text>
						<view class="cus_tag" style="margin-top: 10rpx;">
							<view class="cus_tag_view" v-for="(item, index) in formData['hadUsers1']" :key="item.key">{{
								item.title }}
								<uni-icons type="closeempty" @click="handleCloseTag(index, 1)"
									color='#2979ff'></uni-icons>
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="主题" prop="title" required>
					<uni-easyinput v-model="formData.title" placeholder="请填写主题"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="附件">
					<FileUpload ref="fileUploadRef" :msgId="formData.id" />
				</uni-forms-item>
				<template v-if="ishj">
					<uni-forms-item label="发送时间" prop="send_now" required>
						<radio-group @change="handleChangeSendNow($event, 'send_now')">
							<view>
								<label>
									<radio color="#0097ff" :value="'yes'" :checked="formData.send_now === 'yes'" />立即发送
								</label>
							</view>
							<view style="margin-top: 10rpx;">
								<label style="display: flex;align-items: center;">
									<radio color="#0097ff" :value="'no'" :checked="formData.send_now === 'no'" /> 定时发送
									<view style="display: flex;gap:10rpx;align-items: center;margin-left: 10rpx;"
										@click="showTime = true">
										{{ formData.send_time }}
										<uni-icons type="down"></uni-icons>
									</view>
								</label>
							</view>
						</radio-group>
					</uni-forms-item>
					<uni-forms-item label="回执" prop="receipt_state" required>
						<radio-group @change="handleChangeSendNow($event, 'receipt_state')">
							<label v-for="(item, index) in receipt_stateList" :key="index" 
								style="margin-right: 10rpx;">
								<radio color="#0097ff" :value="item.value" :checked="formData.receipt_state == item.value" />{{ item.label
								}}
							</label>
						</radio-group>
					</uni-forms-item>
					<uni-forms-item label="等级" prop="msg_level" required>
						<radio-group @change="handleChangeSendNow($event, 'msg_level')">
							<label v-for="(item, index) in msg_levelList" :key="index" 
								style="margin-right: 10rpx;">
								<radio color="#0097ff" :value="item.value" :checked="formData.msg_level == item.value" />{{ item.label }}
							</label>
						</radio-group>
					</uni-forms-item>
				</template>
			</uni-forms>
		</view>

		<view class="body_bottom">
			<view @click="handleRefresh">
				刷新
			</view>
			<view @click="handleSave" v-if="type == 'draftbox'">
				保存
			</view>
			<view @click="handleSend" v-if="type == 'draftbox'">
				发送
			</view>
			<view @click="handleResetSend" v-if="type == 'outbox'">
				重新发送
			</view>
			<view @click="handleWithdraw" v-if="type == 'outbox'">
				撤回
			</view>
		</view>
		<MxDatepicker format="yyyy-mm-dd hh:ii" type="datetime" :show="showTime" :value="times" :show-tips="true"
			:show-seconds="false" @confirm="handleConfirmTime" @cancel="showTime = false" />
		<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
		<TkiTree idKey="code" rangeKey="name" :range="departmentList" ref="tkiTreeDepartRef"
			@confirm="handleTkiTreeDepartConfirm" :multiple="true" />
	</view>
</template>

<script>
import {
	postFormAction,
} from '@/utils/request.js';
import {
	msg_levelList,
	receipt_stateList
} from './writebox.js'
import MxDatepicker from '../../component/mx-datepicker/mx-datepicker'
import SelectUser from '@/components/selectUser/index.vue'
import LEditor from '../../component/l-editor/l-editor.vue'
import TkiTree from '@/components/tki-tree/tki-tree.vue'
import FileUpload from '../../component/file-upload/file-upload.vue'
import {
	mapState
} from "vuex";
export default {
	components: {
		MxDatepicker,
		SelectUser,
		LEditor,
		TkiTree,
		FileUpload
	},
	data() {
		return {
			msg_levelList,
			receipt_stateList,
			formData: {
				userRealName: "",
				userRealName1: "",
				userRealName2: "",
				title: "",
				content: "",
			},
			rules: {
				userRealName: {
					rules: [{
						required: true,
						errorMessage: '收件人不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				},
				title: {
					rules: [{
						required: true,
						errorMessage: '主题不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				},
			},
			userType: 0, //0是收件人 1是抄送 2是加密
			url: {
				editDraftPage: '/message_oa/editDraftPage',
				updateDraft: '/message_oa/updateDraft',
				transmit: '/message_oa/transmit',
				recall: '/message_oa/recall',
			},
			ishj: false, //是否高级功能
			iscs: false, //抄送
			isms: false, //密送
			times: null,
			type: '',
			mainId: '',
			showTime: false,
			departmentList: [],
			current: 0, //0发送人 1部门
		}
	},
	onLoad(options) {
		this.type = options.type || ''
		this.mainId = options.mainId || ''
		this.getDepartmentsData()
		this.init()
	},
	computed: {
		...mapState(["emailType"]),
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		handleChangeSendNow(e, col) {
			this.formData[col] = e.detail.value
		},
		init() {
			this.$nextTick(() => {
				setTimeout(async () => {
					try {
						this.$refs.form.clearValidate()
						if (this.type == 'outbox') {
							this.ishj = false;
						} else {
							this.ishj = true;
						}
						uni.showLoading({
							title: '加载中',
							mask: true
						});
						const result = await postFormAction(this.url.editDraftPage, {
							id: this.mainId
						});
						const res = result.data
						this.formData = {
							...res,
							receipt_state: res.receiptState,
							msg_level: res.msgLevel,
							send_now: res.isSent == 1 ? 'yes' : 'no',
							isToOutBox: res.isToOutBox ? 'true' : 'false',
							userRealName: res.realNameJs,
							userRealName1: res.realNameCs,
							userRealName2: res.realNameMs,
							receiver: res.receiversjs,
							receiver1: res.receiverscs,
							receiver2: res.receiversms,
							send_time: res.sendTime,
						};

						if (this.$refs.fileUploadRef) {
							this.$refs.fileUploadRef.fileList = res.attachments || []
						}
						this.formData.hadUsers = []
						this.formData.hadUsers1 = []
						this.formData.hadUsers2 = []
						this.formData.hadDeptList = []
						if (this.formData.receiver) {
							const receivers = this.formData.receiver.split(',')
							const userRealNames = this.formData.userRealName.split(',')
							if (this.formData.receiver.indexOf('dept@') != -1) {
								this.current = 1
								userRealNames.forEach((item, index) => {
									this.formData.hadDeptList.push({
										code: receivers[index].replace('dept@',
											''),
										name: item,
									})
								})
							} else {
								this.current = 0
								userRealNames.forEach((item, index) => {
									this.formData.hadUsers.push({
										key: receivers[index],
										name: receivers[index],
										title: item,
										realName: item,
									})
								})
							}
						}
						if (this.formData.receiver1) {
							this.iscs = true;
							const receivers1 = this.formData.receiver1.split(',')
							const userRealNames1 = this.formData.userRealName1.split(',')
							userRealNames1.forEach((item, index) => {
								this.formData.hadUsers1.push({
									key: receivers1[index],
									name: receivers1[index],
									title: item,
									realName: item,
								})
							})
						} else {
							this.iscs = false;
						}
						if (this.formData.receiver2) {
							this.isms = true;
							const receivers2 = this.formData.receiver2.split(',')
							const userRealNames2 = this.formData.userRealName2.split(',')
							userRealNames2.forEach((item, index) => {
								this.formData.hadUsers2.push({
									key: receivers2[index],
									name: receivers2[index],
									title: item,
									realName: item,
								})
							})
						} else {
							this.isms = false;
						}
						console.log("formData=>", this.formData)
						uni.hideLoading()
					} catch (e) {
						console.log("e", e)
						uni.hideLoading()
					}
				}, 10)
			});
		},
		handleCS() {
			this.iscs = !this.iscs;
			if (!this.iscs) {
				this.formData.userRealName1 = '';
				this.formData.receiver1 = '';
				this.formData.hadUsers1 = []
			}
		},
		handleMS() {
			this.isms = !this.isms;
			if (!this.isms) {
				this.formData.userRealName2 = '';
				this.formData.receiver2 = '';
				this.formData.hadUsers2 = []
			}
		},

		//选择人员
		handleSelectUser(type) {
			this.userType = type
			switch (this.userType) {
				case 0:
					this.$refs.selectUserRef.open({
						users: this.formData['hadUsers']
					})
					break;
				case 1:
					this.$refs.selectUserRef.open({
						users: this.formData['hadUsers1']
					})
					break;
				case 2:
					this.$refs.selectUserRef.open({
						users: this.formData['hadUsers2']
					})
					break;
			}
		},
		//选择用户回调
		handleSelectUserConfirm({
			selectUserList,
			label,
			value
		}) {
			console.log("handleSelectUserConfirm", selectUserList)
			switch (this.userType) {
				case 0:
					this.formData.userRealName = label
					this.formData.receiver = value
					if (Array.isArray(this.formData['hadUsers'])) {
						this.formData['hadUsers'] = this.formData['hadUsers'].concat(selectUserList)
					} else {
						this.formData['hadUsers'] = selectUserList
					}
					this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
					this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
					break;
				case 1:
					this.formData.userRealName1 = label
					this.formData.receiver1 = value
					if (Array.isArray(this.formData['hadUsers1'])) {
						this.formData['hadUsers1'] = this.formData['hadUsers1'].concat(selectUserList)
					} else {
						this.formData['hadUsers1'] = selectUserList
					}
					this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
					this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
					break;
				case 2:
					this.formData.userRealName2 = label
					this.formData.receiver2 = value
					if (Array.isArray(this.formData['hadUsers2'])) {
						this.formData['hadUsers2'] = this.formData['hadUsers2'].concat(selectUserList)
					} else {
						this.formData['hadUsers2'] = selectUserList
					}
					this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
					this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
					break;
			}
			this.$forceUpdate()
		},
		//删除已选用户
		handleCloseTag(index, type) {
			switch (type) {
				case 0:
					this.formData['hadUsers'].splice(index, 1)
					this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
					this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
					break;
				case 1:
					this.formData['hadUsers1'].splice(index, 1)
					this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
					this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
					break;
				case 2:
					this.formData['hadUsers2'].splice(index, 1)
					this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
					this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
					break;
				case 3:
					this.formData['hadDeptList'].splice(index, 1)
					this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
					this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
					break;
			}
			this.$forceUpdate()
		},
		//回调时间
		handleConfirmTime(e) {
			console.log("handleConfirmTime", e)
			const {
				value
			} = e
			this.formData.send_time = value
			this.showTime = false
		},

		//选择部门
		handleTkiTreeDepart() {
			this.$refs.tkiTreeDepartRef._show()
		},
		//部门回调
		handleTkiTreeDepartConfirm(e) {
			let departmentSelected = []
			if (e && e.length) {
				departmentSelected = e
			}
			if (departmentSelected && departmentSelected.length) {
				const codes = this.formData['hadDeptList'].map(item => item.code)
				departmentSelected.forEach(item => {
					if (!codes.includes(item.code)) {
						this.formData['hadDeptList'].push(item)
					}
				})
			}
			this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
			this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
			this.$forceUpdate()

		},
		getDepartmentsData() {
			try {
				let params = {};
				postFormAction('/department/getDepartments', params).then((res) => {
					const {
						data
					} = res
					this.departmentList = data || [];
				});
			} catch (e) {
				console.error(e)
			} finally { }
		},

		handleRefresh() {
			this.init()
		},
		async handleSave() {
			this.$refs.form.validate(async valid => {
				try {
					this.formData.content = this.$refs.lEditorRef.content
					if (!this.formData.content) {
						uni.showToast({
							title: '请输入正文',
							icon: 'none'
						})
						return
					}
					const data = Object.assign({}, this.formData);
					delete data.hadUsers
					delete data.hadUsers1
					delete data.hadUsers2
					delete data.primaryKey
					delete data.hadDeptList
					delete data.attachments
					const fileList = this.$refs.fileUploadRef.fileList
					if (fileList && fileList.length) {
						data.attachments = fileList.map(item => item.id).join(',')
					}
					console.log('data', data);

					uni.showLoading({
						title: '加载中',
						mask: true
					});
					const res = await postFormAction(this.url.updateDraft, data);

					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					this.handleRefresh()
				} catch (error) {
					console.log('handleSave', error);
				} finally {
					uni.hideLoading()
				}
			}).catch(err => {
				console.log('err', err);
			})
		},
		async handleSend() {
			this.$refs.form.validate(async valid => {
				try {
					this.formData.content = this.$refs.lEditorRef.content
					if (!this.formData.content) {
						uni.showToast({
							title: '请输入正文',
							icon: 'none'
						})
						return
					}
					const data = Object.assign({}, this.formData);
					delete data.hadUsers
					delete data.hadUsers1
					delete data.hadUsers2
					delete data.attachments
					delete data.primaryKey
					delete data.hadDeptList
					const fileList = this.$refs.fileUploadRef.fileList
					if (fileList && fileList.length) {
						data.attachments = fileList.map(item => item.id).join(',')
					}
					console.log('data', data);
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					await postFormAction(this.url.transmit, data);
					this.handleReturn()
				} catch (error) {
					console.log('handleSave', error);
				} finally {
					uni.hideLoading()
				}
			}).catch(err => {
				console.log('err', err);
			})
		},
		//重新发送
		handleResetSend() {
			this.handleSend();
		},
		//撤回
		async handleWithdraw() {
			const that = this
			uni.showModal({
				title: "提示",
				content: "您确定撤回么？",
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({
								title: '删除中',
								mask: true
							});
							await postFormAction(that.url.recall, {
								id: that.mainId
							});
							this.handleReturn();
						} catch (e) { } finally {
							uni.hideLoading()
						}
					}
				}
			})
		},
		handleReturn() {
			var pages = getCurrentPages();
			// var currPage = pages[pages.length - 1]; //当前页面
			var prevPage = pages[pages.length - 2]; //上一个页面
			if (prevPage.$vm && prevPage.$vm._ && prevPage.$vm._.exposeProxy) {
				prevPage.$vm._.exposeProxy.isRefresh = true
			}
			uni.navigateBack()
		},
	}
}
</script>

<style lang="scss" scoped>
.content {
	overflow-y: auto;

	&_form {
		padding: 20rpx 20rpx 0;
		margin-bottom: 800rpx;
	}
}

.body_bottom {
	position: fixed;
	z-index: 10;
	bottom: 0;
	height: 100rpx;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-around;
	gap: 20rpx;
	background: #FFFFFF;
	box-shadow: 0rpx -2rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
}
</style>